layui.use(['table', 'form', 'layer','tree'], function () {
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer, $ = layui.$;
    var tree = layui.tree;

    //执行一个 table 实例
    table.render({
        elem: '#demo'
        , url: '/user/userList/' //数据接口
        , id: 'tableReload'
        , title: '用户表'
        , page: true //开启分页
        , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
        , skin: 'row'
        , even: true
        , size: 'lg'
        , limit: 5
        , limits: [5, 10, 20, 30, 50, 100]
        , initSort: {
            field: 'userId' //排序字段，对应 cols 设定的各字段名
            , type: 'desc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
        }
        , cols: [
            [ //表头
                {type: 'checkbox', fixed: 'left'}
                , {field: 'userId', title: '编号', width: '10%', sort: true, fixed: 'left'}
                , {field: 'loginName', title: '登录名', width: '10%', align: 'center'}
                , {field: 'userName', title: '真实姓名', width: '10%', align: 'center'}
                , {
                field: 'sex', title: '性别', width: '10%', align: 'center', templet: function (d) {
                    if (d.sex == 0) {
                        return "男"
                    } else if (d.sex == 1) {
                        return "女"
                    } else {
                        return "未知"
                    }
                }
            }
                , {field: 'phonenumber', title: '手机号', width: '10%', align: 'center'}
                , {field: 'email', title: '邮箱', width: '10%', align: 'center'}
                , {field: 'createBy', title: '创建人', width: '10%', align: 'center'}
                , {field: 'updateBy', title: '修改人', width: '10%', align: 'center'}
                , {
                field: 'status', title: '状态', width: '10%', align: 'center', templet: function (d) {
                    if (d.status == 0) {
                        return "<button class='layui-btn layui-btn-xs layui-btn-radius layui-btn-normal'>正常</button>"
                    } else {
                        return "<button class='layui-btn layui-btn-xs layui-btn-radius layui-btn-danger'>异常</button>"
                    }
                }
            }
                , {
                field: 'deptName', title: '部门名称', width: '10%', align: 'center', templet: function (d) {
                    return d.dept.deptName
                }
            }
                , {field: 'remark', title: '备注', width: '10%', align: 'center'}
                , {fixed: 'right', width: '25%', title: "操作", align: 'center', toolbar: '#barDemo'}
            ]]
    });

    //监听头工具栏事件
    table.on('toolbar(tbl)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id)
            , data = checkStatus.data; //获取选中的数据
        switch (obj.event) {
            case 'add':
                layer.open({
                    type: 1,
                    closeBtn: 2,
                    title: ["保存用户", "color:#009688"],
                    anim: 4,
                    content: $("#save_user_form")
                });
                break;
            case 'update':
                if (data.length === 0) {
                    layer.msg('请选择一行');
                } else if (data.length > 1) {
                    layer.msg('只能同时编辑一个');
                } else {
                    updateModel(data[0]);
                }
                break;
            case 'delete':
                if (data.length === 0) {
                    layer.msg('请选择一行');
                } else {
                    //多行删除确认提示框
                    layer.confirm('确定删除？', {icon: 3, title: '提示'}, function (index) {
                        $.ajax({
                            url: "/user/deleteBatchUser",
                            type: "post",
                            data: JSON.stringify(data),
                            contentType: "application/json;charset=UTF-8",
                            dataType: "json",
                            success: function (result) {
                                if (result.code == 0) {
                                    //关闭弹出层
                                    layer.close(index);
                                    //刷新页面
                                    table.reload('tableReload');
                                    layer.msg('删除成功');
                                }
                            }
                        });
                    });
                }
                break;
        }
    });

    //监听行工具事件
    table.on('tool(tbl)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            , layEvent = obj.event; //获得 lay-event 对应的值
        if (layEvent === 'del') {
            //删除确认提示框
            layer.confirm('确定删除？', {icon: 3, title: '提示'}, function (index) {
                $.ajax({
                    url: "/user/deleteUser",
                    type: "DELETE",
                    data: {"userId": data.userId},
                    dataType: "json",
                    success: function (result) {
                        if (result.code == 0) {
                            //关闭弹出层
                            layer.close(index);
                            //刷新页面
                            table.reload('tableReload');
                            layer.msg('删除成功');
                        }
                    }
                });
            });

        } else if (layEvent === 'edit') {
            updateModel(data);
        } else if (layEvent === 'resetPassword') {
            //重置密码弹出层
            layer.open({
                type: 1,
                closeBtn: 2,
                title: ["重置密码", "color:#009688"],
                anim: 4,
                content: $("#reset_password_form"),
                success: function () {
                    form.val("reset_password_form", {
                        "userId": data.userId
                    });
                }
            });

        }
    });

    //多条件提交按钮监听
    form.on('submit(data-search-btn)', function (data) {
        //获取表单元素值
        var formData = data.field;
        var searchLoginName = formData.searchLoginName;
        var searchUserName = formData.searchUserName;
        var searchPhoneNumber = formData.searchPhoneNumber;

        //重载表格数据
        table.reload('tableReload', {
            where: { //设定异步数据接口的额外参数，任意设
                "searchLoginName": searchLoginName,
                "searchUserName": searchUserName,
                "searchPhoneNumber": searchPhoneNumber
            }
            , page: {
                curr: 1 //重新从第 1 页开始
            }
        });
        return false;//不提交，只传值
    });
    //重置,多条件搜索form表单
    form.on('(search_reset)', function () {
        //重置form表单
        $("#searchForm")[0].reset();

        //刷新页面
        table.reload("tableReload");
    });

    //编辑弹出层
    function updateModel(data) {
        layer.open({
            type: 1,
            closeBtn: 2,
            title: ["编辑用户", "color:#009688"],
            anim: 4,
            content: $("#update_user_form")
        });

        //将信息回显给前台页面
        form.val("update_user_form", {
            "userId": data.userId
            , "loginName": data.loginName
            , "password": data.orderNum
            , "userName": data.userName
            , "email": data.email
            , "phonenumber": data.phonenumber
            , "deptId": data.deptId
            , "status": data.status == 0 ? true : false
            , "sex": data.sex
            , "remark": data.remark
        });

        //设置checkBox回显
        $.ajax({
            url: "/user/getRoleCheckByUserId",
            type: "post",
            data: {"userId": data.userId},
            dataType: "json",
            success: function (result) {
                form.val("update_user_form", result.data);
            }
        });
    }

    //监听保存用户表单的提交
    form.on("submit(userSaveBtn)", function (data) {
        data.field.status = data.field.status ? 0 : 1;
        var checkeds = selectCheckeds("role");//获取被选中的角色
        data.field.salt = checkeds;//盐值在添加/修改时没用，用来存放角色信息

        $.ajax({
            url: "/user/saveUser",
            type: "post",
            data: data.field,
            dataType: "json",
            success: function (result) {
                layer.closeAll();//关闭对话框
                layer.msg(result.msg);
                table.reload("tableReload");//重新加载表格数据
                //重置form表单
                $("#save_user_form")[0].reset();
            }
        });

        return false;
    });

    //监听修改用户表单的提交
    form.on("submit(userUpdateBtn)", function (data) {
        data.field.status = data.field.status ? 0 : 1;
        var checkeds = selectCheckeds();//获取被选中的角色
        data.field.salt = checkeds;//盐值在添加/修改时没用，用来存放角色信息

        $.ajax({
            url: "/user/updateUser",
            type: "post",
            data: data.field,
            dataType: "json",
            success: function (result) {
                layer.closeAll();//关闭对话框
                layer.msg(result.msg);
                table.reload("tableReload");//重新加载表格数据
            }
        });

        return false;
    });

    //获取被选中的复选框
    function selectCheckeds(name) {
        var checkeds = "";
        if (name != null) {
            $("input:checkbox[name='" + name + "']:checked").each(function (i) {
                if (0 == i) {
                    checkeds = $(this).val();
                } else {
                    checkeds += ("," + $(this).val());
                }
            });
        } else {
            $(".role_check:checked").each(function (i) {
                if (0 == i) {
                    checkeds = $(this).val();
                } else {
                    checkeds += ("," + $(this).val());
                }
            });
        }
        return checkeds;
    }

    //监听重置密码的提交
    form.on("submit(formResetPassword-flter)", function (data) {
        $.ajax({
            url: "/user/resetPassword",
            type: "post",
            data: data.field,
            dataType: "json",
            success: function (result) {
                if (result.code == 0) {
                    layer.closeAll();
                    layer.msg(result.msg);
                    $("input[name='password']").val('');
                }
            }
        });
        return false;
    });

    //登录名唯一验证
    $("input[name='loginName']").blur(function () {
        $.ajax({
            url: "/user/checkUserName",
            type: "post",
            data: {"loginName": $(this).val()},
            dataType: "json",
            success: function (result) {
                if (result.code != 0) {
                    $(this).focus();
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
    });

    $(".deptId").click(function () {
       var  index = layer.open({
            title: '选择上级菜单',
            type: 1,
            closeBtn: 2,
            anim: 4,
            content: $('#choose_parent_dept'),
            area: ['400px', '350px']
        });

        $.ajax({
            url: '/SignIn/findDept',
            dataType: 'json',
            contentType: "application/json;charset=UTF-8",
            type: 'GET',
            success: function (result) {
                //基本演示
                tree.render({
                    elem: '#deptTreeChoose'
                    , data: result
                    , showLine: false
                    , onlyIconControl: true
                    , accordion: true
                    , click: function (obj) {

                        form.val("update_user_form",{
                            "deptId":obj.data.id
                        });
                        form.val("save_user_form",{
                            "deptId":obj.data.id
                        });
                        layer.close(index);
                    }
                });

            }
        });
    });
});